<template>
  <article class="page ">
    <headerbar :hideBack="false">
      <!--<div @click="back()" class="back" v-if="!showTitle"><span class="arrow"></span></div>-->
      <div class="message"></div>
      <div class="head-bd">
        互动分享
      </div>
      <div class="message"></div>
      <div @click="goNext('redfriendsRelease')" class="message" slot="btn"><img
        src="../../../../static/images/dangjian/friendscircle/icon-take-photo.png" ></div>
    </headerbar>

    <section class="">

      <div class="text-center no-data" v-if="(tabIndex === 0 || tabIndex === 1) && swipeData.length===0 && showNoData">
        <img src="../../../../static/images/no_data.png" >
        <p>暂无数据</p>
      </div>

      <div class="d-scroll-head list-text" style="" v-if="tabIndex === 0 || tabIndex === 1">
        <cube-scroll
          ref="scroll"
          :scrollEvents="['scroll-end']"
          :options="options"
          @scroll-end="scrollEnd"
          @pulling-up="onPullingUp"
        >
          <div class="circle-item" v-for="(data,index) in swipeData" :key="index">
            <div @click="go('redfriendsAdd', data)" class="avatar-img">
              <img v-if="!data.photo || data.photo === ''" src="../../../../static/images/default.jpg" >
              <img v-if="data.photo && data.photo !== ''" :src="showImg(data.photo)" >
            </div>
            <div class="cont">
              <h2 class="name">{{data.userName}} <redfriendscircleDeleteComponent :currentUserInfo="userInfo" :data="data" :index="index"></redfriendscircleDeleteComponent></h2>
              <!--<p class="tip">{{data.groupName}}</p>-->
              <div class="text-wrap" v-if="!data.isShare || data.isShare==='0'">
                {{data.content}}
              </div>
              <div class="text-wrap" v-if="data.isShare && data.isShare==='1'">
                {{data.friendShare.shareContent}}
                <shareContentInFriend :newsId="data.friendShare.shareContentId" :source="data.friendShare.source" :friendShare="data.friendShare"></shareContentInFriend>
              </div>
              <div class="imgs">
                <div class="img" v-for="(fileId,i) in getFiles(data.files)"><img :src="showImg(fileId)" @click="showImagePreview(fileId)"></div>
              </div>

              <div class="tip date-wrap">
                <span class="date">{{getTime(data.fbsj)}}</span>

                <div class="flex">
                  <div class="icon-live-msg"><img src="../../../../static/images/dangjian/friendscircle/icon-live-msg.png"
                                                  @click="showAlert(data)"></div>
                  <span @click="goEvaluate(data)"><i class="pdh-2 msg-all"></i>全部</span>
                </div>
              </div>

              <div class="like-wrap">
                <div class="icon-like">
                  <img v-if="data.isComment==='0'" src="../../../../static/images/dangjian/friendscircle/icon-like.png" @click="submitComment(data, '', '0')"/>
                  <img v-if="data.isComment==='1'" src="../../../../static/images/dangjian/home/news/icon-like-active.png" />
                </div>
                <span class="pdh-1">{{data.commentNum}}</span>
              </div>

            </div>
          </div>

        </cube-scroll>
      </div>
      <!--红友列表-->
      <section class="d-scroll mgt-2" v-if="tabIndex === 2">
        <section class="people-list ">
          <div v-for="item in frinds" class="people-item block noborder"  @click="goDetail(item.userId)">
            <section class="people-info">
              <div class="avatar-img">
                <img v-if="!item.photo || item.photo === ''" src="../../../../static/images/default.jpg" >
                <img v-if="item.photo && item.photo !== ''" :src="showImg(item.photo)" >
              </div>
              <div class="name">
                {{item.userName}}
              </div>
            </section>
            <div class="btns">
              <div class="btn" @click="showDeleteAlert(item)">删除</div>
            </div>

          </div>

          <p class="pdv-5"></p>
          <p class="pdv-5"></p>
          <div class="text-center no-data" v-if="frinds.length===0 && showNoData">
            <img src="../../../../static/images/no_data.png" >
            <p>暂无数据</p>
          </div>
        </section>
      </section>
    </section>
  </article>
</template>

<script>
  import footerbar from '@/components/layout/footerbar.vue'
  import shareContentInFriend from '@/components/common/shareContentInFriend.vue'
  import tools from '@/utils/tools'
  import api from '@/common/config/api'
  import loginService from '@/service/loginService'
  import moment from 'moment'
  import ups from '@/components/common/upsComponent'
  import redfriendscircleDeleteComponent from './redfriendscircleDeleteComponent'
  export default {
    components: {footerbar, shareContentInFriend, ups, redfriendscircleDeleteComponent},
    name: 'redfriendscircle',
    data () {
      return {
        userInfo: {},
        swipeData: [],
        options: {
          pullUpLoad: true,
          scrollbar: false
        },
        pageIndex: 1,
        tabIndex: 0,
        currentIndex: 0,
        tipMessage: '',
        from: '',
        title: '',
        showTitle: false,
        showMenu: true,
        needRefresh: false,
        frinds: [],
        showNoData: false
      }
    },
    created () {
      this.init()
    },
    mounted () {
      console.log('mounted', this.scrollToY)
      if (this.scrollToY) {
        setTimeout(() => {
          this.scrollTo()
        }, 10)
      }
    },
    methods: {
      init () {
        this.from = this.$route.params.from
        if (this.$route.query.type == 2) {
          this.showMenu = false
          this.tabIndex = 0
        }
        this.userInfo = this.$localStorage.get('userInfo')
        this.loadData(0)
        this.fetchUserInfo()
      },
      scrollEnd (pos) {
        console.log('scrollEnd', pos)
        this.scrollToY = pos.y
      },
      scrollTo () {
        this.$refs.scroll.scrollTo(
          0,
          this.scrollToY,
          0,
          ''
        )
      },
      fetchUserInfo () {
        if (this.$route.query.type == 2 && this.$route.query.userId) {
          return this.fetchService.getUserInfoById(this.$route.query.userId).then(res => {
            if (res.code !== 0) {
              return
            }
            this.userInfo = res.data
            this.userInfo.nickname = res.data.nickname || res.data.fullname
          })
        }
        this.userInfo = this.$localStorage.get('userInfo')
      },
      go (name, data) {
        if (this.from === 'workVillage') {
          return
        }
        if (this.tabIndex === 1 || this.userInfo.id === data.userId) {
          return
        }
        this.$store.state.redfriendsAdd = data
        this.$router.push({name: name})
      },
      goNext (name) {
        this.$router.push({path: `/redfriendsRelease/${this.from}`})
      },
      goMyCircle (userInfo) {
        let myInfo = this.tools.getUserInfo()
        if (userInfo.id !== myInfo.id) {
          return false
        }
        this.$router.push({name: `redfriendscircle`, query: {type: 2}, params: {from: 'home'}})
      },
      goApplication () {
        this.$router.push({path: `/applicationList`})
      },
      onPullingUp () {
        console.log('onPullingUp')
        this.loadData(this.tabIndex)
      },
      loadData (index) {
        this.showNoData = false
        if (this.currentIndex !== index) {
          this.pageIndex = 1
          this.swipeData = []
        }
        this.currentIndex = this.tabIndex = index
        let isFriend
        if (index === 0) {
          isFriend = '0'
        } else {
          isFriend = '1'
        }
        let data = {
          page: this.pageIndex,
          limit: 10,
          isFriend: isFriend
        }
        this.title = '互动分享'
        this.showTitle = false
        this.getFriendsShare(data)
      },
      getTime (createTime) {
        return moment(createTime).format('MM-DD HH:mm')
      },
      showAlert (data) {
        this.dialog = this.$createDialog({
          type: 'prompt',
          title: '评论',
          prompt: {
            value: '',
            placeholder: '评论'
          },
          onConfirm: (e, promptValue) => {
            this.submitComment(data, promptValue, '2')
            console.log('this.comment=', this.comment)
          }
        }).show()
      },
      submitComment (data, promptValue, commentWay) {
        let paramData = {
          content: promptValue,
          commentWay: commentWay,
          friendNewsId: data.id
        }
        this.shareFriendComment(paramData, data)
      },
      getFiles (files) {
        if (!files || files.trim() === '') {
          return []
        }
        return files.split(',')
      },
      showImg (fileId) {
        let fileUrl = this.tools.getImgUrl(fileId)
        console.log('-------------fileUrl=', fileUrl)
        return fileUrl
      },
      getFriends (data) { // 红友圈
        loginService.friendNews(data).then((res) => {
          if (res.code === 0 && res.data.length < 1) {
            this.$refs.scroll && this.$refs.scroll.forceUpdate && this.$refs.scroll.forceUpdate(true, false)
            return tools.tip('已无更多数据')
          }
          this.pageIndex++
          this.swipeData = this.swipeData.concat(res.data)
          this.$store.state.redfriendscircleList = this.swipeData
          setTimeout(() => {
            this.$refs.scroll && this.$refs.scroll.forceUpdate && this.$refs.scroll.forceUpdate(true, false)
            this.options.isPullUpLoad = false
          }, 100)
        })
      },
      getFriendsShare (data) { // 互动分享
        loginService.shareFriendNews(data).then((res) => {
          this.showNoData = true
          if (res.code === 0 && res.data.length < 1) {
            this.$refs.scroll.forceUpdate && this.$refs.scroll.forceUpdate()
            return tools.tip('已无更多数据')
          }
          this.pageIndex++
          this.swipeData = this.swipeData.concat(res.data)
          setTimeout(() => {
            this.$refs.scroll.forceUpdate && this.$refs.scroll.forceUpdate(true, false)
            this.options.isPullUpLoad = false
          }, 100)
        })
      },
      friendComment (paramData, data) { // 红友圈评论
        loginService.friendComment(paramData).then((res) => {
          if (res.code === 0) {
            if (paramData.commentWay === '0') {
              tools.tip('点赞成功')
            } else if (paramData.commentWay === '2') {
              tools.tip('评论成功')
            }
            data.isComment = '1'
            data.commentNum = data.commentNum + 1
          } else {
            tools.tip(res.message)
          }
          // this.pageIndex = 1
          // this.swipeData = []
          // this.loadData(this.currentIndex)
        })
      },
      shareFriendComment (paramData, data) { // 互动分享评论
        loginService.shareFriendComment(paramData).then((res) => {
          if (res.code === 0) {
            if (paramData.commentWay === '0') {
              tools.tip('点赞成功')
            } else if (paramData.commentWay === '2') {
              tools.tip('评论成功')
            }
            // this.pageIndex = 1
            // this.swipeData = []
            // this.loadData(this.currentIndex)
            data.isComment = '1'
            data.commentNum = data.commentNum + 1
          } else {
            tools.tip(res.message)
          }
        })
      },
      back () {
        this.tools.back()
      },
      goEvaluate (data) {
        this.$localStorage.set('evaluateData', data)
        this.$router.push({path: `/evaluate`})
      },
      showImagePreview (fileId) {
        if (fileId.length < 1) {
          return false
        }
        let fileUrl = this.tools.getImgUrl(fileId)
        let imgs = [fileUrl]
        this.$createImagePreview({
          initialIndex: 0,
          imgs: imgs
        }, (h) => {
          return h('div', {
            class: {
              'image-preview-custom-header': false
            },
            slot: 'header'
          }, '')
        }).show()
      },
      getMyFriends () {
        this.tabIndex = 2
        this.currentIndex = 2
        let data = {
          page: 1,
          limit: 1000,
          params: {}
        }
        this.fetchService.friends(data).then(res => {
          if (res.code !== 0) {
            return tools.tip(res.message)
          }
          console.log(res)
          this.frinds = res.data
        })
      },
      showDeleteAlert (item) {
        let me = this
        this.$createDialog({
          type: 'confirm',
          title: '确定删除好友？',
          content: '',
          confirmBtn: {
            text: '确定',
            active: true,
            disabled: false,
            href: 'javascript:;'
          },
          cancelBtn: {
            text: '取消',
            active: false,
            disabled: false,
            href: 'javascript:;'
          },
          onConfirm: () => {
            me.deletefriend(item)
          },
          onCancel: () => {
          }
        }).show()
      },
      deletefriend (item) {
        this.fetchService.deletefriend(item.id).then(res => {
          if (res.code !== 0) {
            return tools.tip(res.message)
          }
          tools.tip('删除成功！')
          this.getMyFriends()
        })
      },
      goDetail (id) {
        this.$router.push({path: `/friendInfo/${id}`})
      },
      /*暂存数据*/
      storeData () {
        let storeKeys = [
          'userInfo',
          'swipeData',
          'pageIndex',
          'tabIndex',
          'currentIndex',
          'tipMessage',
          'from',
          'title',
          'showTitle',
          'showMenu',
          'frinds',
          'showNoData',
          'scrollToY'
        ]
        this.tools.storeData(this, storeKeys)
      },
      onRouteChange (vm) {
        let to = vm.$route
        if (vm.$route.query.type) {
          vm.needRefresh = true
          vm.pageIndex = 1
          vm.swipeData = []
          vm.init()
        } else if (vm.needRefresh) {
          console.log('refresh home')
          vm.currentIndex = 0
          vm.showTitle = false
          vm.showMenu = true
          vm.needRefresh = false
          vm.pageIndex = 1
          vm.swipeData = []
          vm.init()
        }
      }
    },
    watch: {
      $route (to, from) {
        if (to.name !== from.name) {
          return false
        }
        // 只处理内部跳转
        this.onRouteChange(this)
      }
    },
    beforeRouteUpdate (to, from, next) {
      console.log('beforeRouteUpdate', to)
      // 长时间未进入删除缓存数据
      let outTime = 300 * 1000
      if (Date.now() - this.tools.resumeStoreData(this)._storeTime > outTime) {
        this.tools.clearStoreData(this)
        this.init()
      }
      next()
    },
    beforeRouteEnter (to, from, next) {
      console.log('beforeRouteEnter', to)
      next(vm => {
        console.log('beforeRouteEnter2', vm)
        vm.onRouteChange(vm)
      })
    },
    beforeRouteLeave (to, from, next) {
      console.log('beforeRouteLeave')
      this.storeData()
      next()
    }
  }
</script>

<style scoped lang="scss">
  @import "@/common/stylus/moon.scss";
  .mine-page {
    background: url("../../../../static/images/dangjian/mine/bg-mine-hd.png") #F5F5F5 no-repeat top center;
    background-size: 100% auto;
    padding: 0;
    .header {
      background: none;
      justify-content: space-between;
      margin-bottom: pxToRem(40px);
    }
  }
  .cont {
    flex: 1;
  }
</style>

